package com.simple.jvm;

import com.simple.jvm.two.MyJavaTestFile;
import org.apache.commons.io.IOUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * 项目: question-study-improve
 *
 * 功能描述:
 *
 * @author: WuChengXing
 *
 * @create: 2024-04-15 17:08
 **/
public class LocalClassloader extends ClassLoader {

    private String byteCodePath;

    public LocalClassloader(String byteCodePath) {
        this.byteCodePath = byteCodePath;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        Class<?> cls = findLoadedClass(name);
        if (cls != null) {
            return cls;
        }

        if (!name.startsWith("My")) {
            return super.loadClass(name);
        }

        try {
            String filePath = byteCodePath + name.replace(".", "/") + ".class";
            System.out.println("byte code path:" + filePath);
            InputStream is = new FileInputStream(filePath);
            byte[] bytes = IOUtils.toByteArray(is);
            return defineClass(null, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return super.loadClass(name);
    }

    public static void main(String[] args) {
        LocalClassloader localClassloader = new LocalClassloader("/Users/chengxingwu/project/person-project/qai/target/classes/com/simple/jvm/two/");
        try {
            Class myJavaTestFile = localClassloader.loadClass("MyJavaTestFile");
            try {
                Object o = myJavaTestFile.newInstance();
                System.out.println(myJavaTestFile.getClassLoader().getClass().getName());
                MyJavaTestFile myJavaTestFile1 = new MyJavaTestFile();
                System.out.println(myJavaTestFile1.getClass().getClassLoader().getClass().getName());
                Method testClassLoader = myJavaTestFile.getMethod("testClassLoader", null);
                System.out.println(testClassLoader.invoke(o, null));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
